package com.jshan.blog.exception;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import com.jshan.blog.enums.BizCodeEnums;
import com.jshan.blog.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;

/**
 * 集中处理所有异常
 */
@Slf4j
@RestControllerAdvice(annotations = RestController.class)
public class ExceptionControllerAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result handleValidException(MethodArgumentNotValidException e){
        log.error("数据校验出现问题:{},异常类型:{}",e.getMessage(),e.getClass());
        BindingResult bindingResult = e.getBindingResult();
        HashMap<String, String> map = new HashMap<>();
        bindingResult.getFieldErrors().forEach(fieldError -> {
            map.put(fieldError.getField(), fieldError.getDefaultMessage());
        });
        return Result.fail(BizCodeEnums.VALID_EXCEPTION.getCode(),BizCodeEnums.VALID_EXCEPTION.getMsg(), map);
    }
    @ExceptionHandler(NotPermissionException.class)
    public Result handleSaException(NotPermissionException e) {
        // 自定义错误信息
        // String customErrorMessage = "自定义权限错误信息: " + e.getMessage();
        log.error("没有权限:{}",e.getMessage());
        // log.info("exception:{}",e.getCode());
        return Result.fail(BizCodeEnums.UN_PERM.getCode(), BizCodeEnums.UN_PERM.getMsg());
    }
    @ExceptionHandler(NotLoginException.class)
    public Result handleNotSaException(NotLoginException e) {
        log.error("您还没有登录:{}",e.getMessage());
        return Result.fail(BizCodeEnums.NO_LOGIN.getCode(), BizCodeEnums.NO_LOGIN.getMsg());
    }

    // 全局的异常处理
    // @ExceptionHandler(value = Throwable.class)
    // public Result handleException(Throwable e){
    //     log.error("系统出错啦！错误信息:{}",e.getMessage());
    //     e.printStackTrace();
    //     return Result.fail(BizCodeEnums.UNKNOWN_EXCEPTION.getCode(),e.getMessage());
    // }
}
